//
//  BanBu_SnapController.m
// Halfarea
//
//  Created by Wang Xj on 14-1-14.
//
//

#import "BanBu_SnapController.h"
#import <ImageIO/ImageIO.h>
#import "PBJViewController.h"
#import "BanBuAPIs.h"
#import "UIViewController+Animation.h"
#import "BanBu_SendMsg.h"

@interface BanBu_SnapController ()
{
    AVCaptureSession *_session;
    AVCaptureDeviceInput *_captureInput;
    AVCaptureStillImageOutput *_captureOutput;
    AVCaptureVideoPreviewLayer *_preview;
    AVCaptureDevice *_device;
    
    UIImage *_finishImage;
}
@end

@implementation BanBu_SnapController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (__MainScreen_Height<500)
    {
        CGRect frame = self.buttonView.frame;
        frame.origin.y = __MainScreen_Height-80;
        self.buttonView.frame =frame;
    }
    
    self.timePicker.hidden = YES;
    
    //初始化摄像头
    [self initialize];
    
    //初始化视频frame
//    self.cameraView.frame = CGRectMake(0, 70, 320, __MainScreen_Height-70);
    
    _preview = [AVCaptureVideoPreviewLayer layerWithSession: _session];
    _preview.frame = CGRectMake(0, 0, self.cameraView.frame.size.width, self.cameraView.frame.size.height);
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    [self.cameraView.layer addSublayer:_preview];
    
    _timePicker.hidden = YES;
    [self.cameraView bringSubviewToFront:_timePicker];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setTimePickerHidden)];
    [self.cameraView addGestureRecognizer:tap];
    [tap release];
    
    _setTimeButton.hidden = YES;
    [_session startRunning];
    [self initTimePicker];
}

-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidUnload
{
    [self setButtonView:nil];
    [self setSaveButtonview:nil];
    [self setExchangeButton:nil];
    [self setTimePicker:nil];
    [self setSetTimeButton:nil];
    [self setTimeLabel:nil];
    [self setButtonView:nil];
    [super viewDidUnload];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"videoNotifi" object:nil];
    [_session release],_session = nil;
    [_finishImage release],_finishImage = nil;
    [_captureOutput release],_captureOutput = nil;
    
    [_cameraView release],_cameraView = nil;
    [_cancelButton release],_cancelButton = nil;
    [_takePhotoButton release],_takePhotoButton = nil;
    [_saveButton release],_saveButton = nil;
    [_positionButton release],_positionButton = nil;
    [_flashButton release],_flashButton = nil;

    [_buttonView release],_buttonView = nil;
    [_saveButtonview release],_saveButtonview = nil;
    [_exchangeButton release],_exchangeButton = nil;
    
    [_timePicker release];
    [_setTimeButton release];
    [_timeLabel release];
    [_buttonView release];
    [super dealloc];
}



//初始化摄像头
- (void) initialize
{
    //1.创建会话层
    _session = [[AVCaptureSession alloc] init];
    [_session setSessionPreset:AVCaptureSessionPreset640x480];
    
    //2.创建、配置输入设备
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    [_device lockForConfiguration:nil];
    if([_device flashMode] == AVCaptureFlashModeOff){
        [_flashButton setImage:[UIImage imageNamed:@"flash-off.png"] forState:UIControlStateNormal];
    }
    else if([_device flashMode] == AVCaptureFlashModeAuto){
        [_flashButton setImage:[UIImage imageNamed:@"flash-auto.png"] forState:UIControlStateNormal];
    }
    else{
        [_flashButton setImage:[UIImage imageNamed:@"flash.png"] forState:UIControlStateNormal];
    }
    [_device unlockForConfiguration];
    
	NSError *error;
	_captureInput = [AVCaptureDeviceInput deviceInputWithDevice:_device error:&error];
	if (!_captureInput)
	{
		NSLog(@"Error: %@", error);
		return;
	}
    [_session addInput:_captureInput];
    
    
    //3.创建、配置输出
    _captureOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil];
    [_captureOutput setOutputSettings:outputSettings];
	[_session addOutput:_captureOutput];
}

#pragma mark -

- (void)addHollowOpenToView:(UIView *)view
{
    CATransition *animation = [CATransition animation];
    animation.duration = 0.5f;
    animation.delegate = self;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.fillMode = kCAFillModeForwards;
    animation.type = @"cameraIrisHollowOpen";
    [view.layer addAnimation:animation forKey:@"animation"];
}

- (void)addHollowCloseToView:(UIView *)view
{
    CATransition *animation = [CATransition animation];//初始化动画
    animation.duration = 0.5f;//间隔的时间
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = @"cameraIrisHollowClose";
    
    [view.layer addAnimation:animation forKey:@"HollowClose"];
}

#pragma mark - 按钮响应事件

//切换视频、拍照
- (IBAction)showTimePicker:(UIButton *)sender
{
    _timePicker.hidden = NO;
    [self.cameraView bringSubviewToFront:_timePicker];
}
#pragma mark - 切换视频、拍照
- (IBAction)exchangeVideoAndPhoto:(UIButton *)sender
{
    //切换为拍照，按钮显示为video
    PBJViewController * pbjController = [[PBJViewController alloc]init];
    pbjController.quote = @"snap";
    
    [self.navigationController pushViewController:pbjController animated:NO];
    [pbjController release];
}

//取消拍照、拍视频并返回上级界面
- (IBAction)cancelTakePhoto:(UIButton *)sender
{
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController dismissViewControllerAnimated:YES];
}

//拍照
- (IBAction)takePhoto:(id)sender
{
    _setTimeButton.hidden = NO;
    self.timeLabel.hidden = NO;
    self.timeLabel.text = [NSString stringWithFormat:@"%d",sendMsgManager.effectiveTime];
    
    if (_finishImage)
    {
        return;
    }
    
//    [self addHollowCloseToView:self.cameraView];
    
    //get connection
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in _captureOutput.connections) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection) { break; }
    }
    
    [self addHollowOpenToView:self.cameraView];
    
    //get UIImage
    [_captureOutput captureStillImageAsynchronouslyFromConnection:videoConnection
                                                completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
                                                    _saveButton.hidden = NO;
                                                    _cancelButton.hidden = NO;
                                                    _setTimeButton.hidden = NO;
                                                    _takePhotoButton.hidden = YES;
                                                    
//                                                    [self addHollowCloseToView:self.cameraView];
                                                    [_session stopRunning];
//                                                    [self addHollowOpenToView:self.cameraView];
                                                    
                                                    NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
                                                    _finishImage = [[UIImage alloc] initWithData:imageData] ;
                                                }];
}

#pragma mark - 闪光灯设置
- (IBAction)changeFlash:(id)sender
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    BOOL on = YES;
    if ([device torchMode] == 0)
    {
        on = YES;
    }
    else
    {
        on = NO;
    }
    
    if ([device hasTorch])
    {
        [device lockForConfiguration:nil];
        if (on)
        {
            [device setTorchMode: AVCaptureTorchModeOn];
            [_flashButton setImage:[UIImage imageNamed:@"flash.png"] forState:UIControlStateNormal];
        }
        else
        {
            [device setTorchMode: AVCaptureTorchModeOff];
            [_flashButton setImage:[UIImage imageNamed:@"flash-off.png"] forState:UIControlStateNormal];
        }
        
        [device unlockForConfiguration];
    }
}

#pragma mark - 切换前后镜头
- (IBAction)positionCnange:(id)sender
{
    NSArray *inputs = _session.inputs;
    for ( AVCaptureDeviceInput *input in inputs )
    {
        AVCaptureDevice *device = input.device;
        if ([device hasMediaType:AVMediaTypeVideo])
        {
            AVCaptureDevicePosition position = device.position;
            AVCaptureDevice *newCamera = nil;
            AVCaptureDeviceInput *newInput = nil;
            if (position == AVCaptureDevicePositionFront)
            {
                newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            }
            else
            {
                newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            }
            
            newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
            //2014年10月09日16:23:59 by yinlinlin 判断前后镜头是否能够切换,不能切换，不执行
            if (!newInput)
            {
                return;
            }
            _device = newCamera;
            //添加动画
            CATransition *animation = [CATransition animation];
            animation.delegate = self;
            animation.duration = .8f;
            animation.timingFunction = UIViewAnimationCurveEaseInOut;
            animation.type = @"oglFlip";
            if (_device.position == AVCaptureDevicePositionFront) {
                animation.subtype = kCATransitionFromRight;
            }
            else if(_device.position == AVCaptureDevicePositionBack){
                animation.subtype = kCATransitionFromLeft;
            }
            [_preview addAnimation:animation forKey:@"animation"];
            // beginConfiguration ensures that pending changes are not applied immediately
            [_session beginConfiguration];
            
            [_session removeInput:input];
            [_session addInput:newInput];
            
            // Changes take effect once the outermost commitConfiguration is invoked.
            
            [_session commitConfiguration];
            break;
        }
    }
}

//切换镜头
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices)
    {
        if (device.position == position)
        {
            return device;
        }
    }
    return nil;
}

//保存图片
- (IBAction)saveAction:(id)sender
{    
    _finishImage = [self composeImage:nil toImage:_finishImage atFrame:CGRectZero];
    [self image:_finishImage didFinishSavingWithError:nil contextInfo:nil];
    
//    UIImageWriteToSavedPhotosAlbum(_finishImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    _saveButton.hidden = YES;
    _cancelButton.hidden = YES;
    _setTimeButton.hidden = YES;
    _timeLabel.hidden = YES;
    _timePicker.hidden = YES;
    _takePhotoButton.hidden = NO;
    [_session startRunning];
}

//合并两张图
- (UIImage *)composeImage:(UIImage *)subImage toImage:(UIImage *)superImage atFrame:(CGRect)frame
{
    CGSize superSize = superImage.size;
    
    CGFloat widthScale = frame.size.width / self.cameraView.frame.size.width;
    CGFloat heightScale = frame.size.height / self.cameraView.frame.size.height;
    
    CGFloat x = (int)frame.origin.x % 320;
    
    CGRect subFrame = CGRectMake(x, frame.origin.y, widthScale * superSize.width, heightScale * superSize.height);
    
    UIGraphicsBeginImageContext(superSize);
    [superImage drawInRect:CGRectMake(0, 0, superSize.width, superSize.height)];
    [subImage drawInRect:subFrame];
    
    __autoreleasing UIImage *finish = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return finish;
}

//保存后操作
-(void) image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error != NULL)
    {
        NSLog(@"save error");
        _finishImage= nil;
        [self cancelAction:nil];
    }
    else
    {
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:_finishImage,@"snapImage",[NSNumber numberWithInt:1],KeyType,@"snap",KeyShowFrom,self.timeLabel.text,KeyEffectiveTime, nil];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:kSendMsgAllTypeNotification object:dic];
        _finishImage= nil;
        [self cancelTakePhoto:nil];
    }
}

-(IBAction)cancelAction:(id)sender
{
    _finishImage = nil;
    _saveButton.hidden = YES;
    _cancelButton.hidden = YES;
    _timePicker.hidden = YES;
    _setTimeButton.hidden = YES;
    _takePhotoButton.hidden = NO;
    self.timeLabel.hidden = YES;
    self.timeLabel.text = nil;
    [_session startRunning];
}

#pragma mark - UIPickerViewDataSource
-(void)initTimePicker
{
    if(sendMsgManager.effectiveTime<3)
    {
        sendMsgManager.effectiveTime = 3;
    }
    self.timeArray = [NSArray arrayWithObjects:@"3s",@"4s",@"5s",@"6s",@"7s",@"8s",@"9s",@"10s", nil];
    [self.cameraView bringSubviewToFront:_setTimeButton];
    [self.cameraView bringSubviewToFront:_timeLabel];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}


- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component)
    {
        case 0:
            return self.timeArray.count;
            break;
        default:
            return 4;
            break;
    }
}

#pragma mark -
#pragma mark UIPickerViewDelegate

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [self.timeArray objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self.timeLabel.text = [self.timeArray objectAtIndex:row];
    sendMsgManager.effectiveTime = [self.timeLabel.text integerValue];
}

-(void)setTimePickerHidden
{
    if (!_timePicker.hidden)
    {
        _timePicker.hidden = YES;
    }
}
@end
